package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {
        TradeVo tradeVo = new TradeVo();
        //首先获得用户id，通过用户id远程调用购物车模块，获取一切信息
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId,SecurityConstants.INNER);
        if (cartCheckedListResult.getCode() == R.FAIL){
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedListResult.getData();

        //将cartInfoList的数据放在OrderItem中
         List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
             OrderItem orderItem = new OrderItem();
             BeanUtils.copyProperties(cartInfo,orderItem);
             return orderItem;
         }).toList();
         //获得总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //设置流水号
        String userTradeKey = "user:tradeNo:" + userId; //流水好key
        String tradeNo = UUID.randomUUID().toString().replaceAll("-",""); //流水号值
        redisTemplate.opsForValue().set(userTradeKey,tradeNo);//存入redis

        //把数据全塞进tradeVo中
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
    //1 检验是否重复提交订单
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;

        /*//比较和删除不是原子性，该方法不安全，pass掉
        String tradeNoFromForm = orderForm.getTradeNo();
        String tradeNoFromRedis = (String) redisTemplate.opsForValue().get(userTradeKey);
        if (Objects.equals(tradeNoFromRedis,tradeNoFromForm)){
            throw new ServiceException("不能重复提交");
        }
        //第一次进来，redis中的流水号还在，比较之后，立马把redis中的流水号删除。用来过滤之后来的提交，redis中没有redis
        //说明已经已经存在正在提交的线程，则不可重复提交
        redisTemplate.delete(userTradeKey);*/

        //通过LUA脚本保证判断和删除 具有原子性。
        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call('del',KEYS[1]);\n" +
                "else\n" +
                "    return 0;\n" +
                "end;";

        String tradeNoFromForm = orderForm.getTradeNo();
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script,Long.class);
        Long result = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNoFromForm);
        if(result == 0){
            throw new ServiceException("请不要重复提交订单");
        }


   //2 检验表单是否为空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("表单中没有数据");
        }

    //3 检验最新价格和购物车传来的价格是否一致
        //先获取skuId集合
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        //获取做新价格
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList,SecurityConstants.INNER);
        if (skuPriceListResult.getCode() == R.FAIL){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();

        Map<Long, BigDecimal> skuPriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        StringBuffer stringBuffer = new StringBuffer();
        for (OrderItem orderItem : orderItemList) {
            int i = orderItem.getSkuPrice().compareTo(skuPriceMap.get(orderItem.getSkuId()));//最新价格和购物车价格比较
            if(i!=0){ //如果不等于1，则说明价格不一致，所以要更新购物车价格
                /*remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                throw new ServiceException("价格有变动");*/ //自己的想法
                stringBuffer.append("[").append(orderItem.getSkuName()).append("]").append("价格有变动");
            }
        }

        if (!stringBuffer.toString().isEmpty()){
            throw new ServiceException(stringBuffer.toString());
        }
    //4 价格一致，锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        remoteProductService.checkAndLock(orderForm.getTradeNo(),skuLockVoList,SecurityConstants.INNER);

    //5 将订单数据存入数据库 订单表，订单项表，订单日志表
        Long orderId = null;//订单id是存入数据库时，主键自增生成的订单id
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            //下单失败：解锁库存

            throw new ServiceException("下单失败");
        }

    //6 删除购物车
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);
        return orderId;
    }

    @Transactional
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1.保存订单基本信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setOrderNo(orderForm.getTradeNo()); //交易流水号作为订单号

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付金额
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总金额  不包括 运费 和 优惠价
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】

        UserAddress userAddress = remoteUserAddressService
                .getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();

        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        orderInfo.setRemark(orderForm.getRemark());

        orderInfo.setCouponAmount(new BigDecimal(0));   //优惠卷金额

        orderInfoMapper.insert(orderInfo); //主键回填   数据库分配主键

        //2.保存订单项信息
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //3.保存订单日志信息
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setOperateUser("用户");
        orderLog.setProcessStatus(0);
        orderLog.setNote("用户下单");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }
}